<?php

namespace App\Modules\Apicrzs\Http\Middleware;

use App\Exceptions\Exception;
use App\Traits\CryptAES;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Config;
use Symfony\Component\HttpFoundation\Response;
use function App\Http\Middleware\error;

class InitMiddleware
{
    /**
     * @param Request $request
     * @param Closure $next
     * @param $type
     * @return Response
     * @throws Exception
     */
    public function handle(Request $request, Closure $next, $type = null): Response
    {
        [$platform,$system,$version] = explode('/', $request->header('user-agent'));
        Config::set('init.platform',$platform);
        Config::set('init.system',$system);
        Config::set('init.version',$version);
        $token = $request->header('token');
        try {
            $info = CryptAES::decryptToken($token, $type);
            $guid = Arr::get($info,'data.user_id',0);
            Config::set('init.guid',$guid);
            return $next($request);
        } catch (Exception $e) {
            return error($e->getMessage(),$e->getCode());
        }
    }
}
